<div th:fragment="content">
    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">停车记录管理</h5>
            <button class="btn btn-primary" id="addRecordBtn">新增停车记录</button>
        </div>
        <div class="card-body">
            <form id="searchForm" class="row g-3 mb-3">
                <div class="col-md-3">
                    <input type="text" class="form-control" name="plateNumber" placeholder="车牌号">
                </div>
                <div class="col-md-3">
                    <input type="text" class="form-control" name="spaceNumber" placeholder="车位号">
                </div>
                <div class="col-md-3">
                    <select class="form-select" name="status">
                        <option value="">全部状态</option>
                        <option value="1">停车中</option>
                        <option value="2">已离场</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <button type="button" class="btn btn-primary" onclick="search()">搜索</button>
                    <button type="button" class="btn btn-secondary" onclick="resetSearch()">重置</button>
                </div>
            </form>
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>车牌号</th>
                            <th>车位号</th>
                            <th>入场时间</th>
                            <th>出场时间</th>
                            <th>停车时长(分钟)</th>
                            <th>费用(元)</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="dataTable">
                        <!-- 数据通过JS加载 -->
                    </tbody>
                </table>
            </div>
            <nav>
                <ul class="pagination justify-content-center" id="pagination"></ul>
            </nav>
        </div>
    </div>
    <!-- 新增/编辑模态框 -->
    <div class="modal fade" id="recordModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="recordForm">
                    <input type="hidden" id="id" name="id">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalTitle">新增停车记录</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">停车场</label>
                            <select class="form-select" id="lotId" name="lotId" required></select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">车位</label>
                            <select class="form-select" id="spaceId" name="spaceId" required></select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">车辆</label>
                            <select class="form-select" id="vehicleId" name="vehicleId" required></select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">用户</label>
                            <select class="form-select" id="userId" name="userId" required></select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">入场时间</label>
                            <input type="datetime-local" class="form-control" id="entryTime" name="entryTime" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">出场时间</label>
                            <input type="datetime-local" class="form-control" id="exitTime" name="exitTime">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">状态</label>
                            <select class="form-select" id="status" name="status" required>
                                <option value="1">停车中</option>
                                <option value="2">已离场</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="save()">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script>
let currentPage = 1;
const pageSize = 10;
let modal;

$(function() {
    modal = new bootstrap.Modal(document.getElementById('recordModal'));
    $('#addRecordBtn').on('click', openAddModal);
    loadData();
    loadAllLots();
    loadAllUsers();

    $('#lotId').on('change', function() {
        const lotId = $(this).val();
        if (lotId) {
            loadSpacesByLotId(lotId);
        } else {
            $('#spaceId').empty();
        }
    });

    $('#userId').on('change', function() {
        const userId = $(this).val();
        if (userId) {
            loadVehiclesByUserId(userId);
        } else {
            $('#vehicleId').empty();
        }
    });
});

function loadData() {
    const params = $('#searchForm').serialize() + `&pageNum=${currentPage}&pageSize=${pageSize}`;
    $.get('/api/parking-record/page?' + params, function(res) {
        if (res.code === 200) {
            console.log('Received data:', res.data.records);
            renderTable(res.data.records);
            renderPagination(res.data);
        } else {
            alert(res.message);
        }
    });
}

function renderTable(data) {
    const tbody = $('#dataTable');
    tbody.empty();
    data.forEach(item => {
        tbody.append(`
            <tr>
                <td>${item.id}</td>
                <td>${item.plateNumber}</td>
                <td>${item.spaceId}</td>
                <td>${item.entryTime}</td>
                <td>${item.exitTime || ''}</td>
                <td>${item.duration !== null ? item.duration : ''}</td>
                <td>${item.fee !== null ? item.fee : ''}</td>
                <td>${item.status === 1 ? '停车中' : '已离场'}</td>
                <td>
                    <button class="btn btn-sm btn-warning" onclick="openEditModal(${item.id})">编辑</button>
                    <button class="btn btn-sm btn-danger" onclick="deleteItem(${item.id})">删除</button>
                </td>
            </tr>
        `);
    });
}

function renderPagination(page) {
    const pagination = $('#pagination');
    pagination.empty();
    pagination.append(`
        <li class="page-item ${page.current === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${page.current - 1})">上一页</a>
        </li>
    `);
    for (let i = 1; i <= page.pages; i++) {
        pagination.append(`
            <li class="page-item ${page.current === i ? 'active' : ''}">
                <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
            </li>
        `);
    }
    pagination.append(`
        <li class="page-item ${page.current === page.pages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${page.current + 1})">下一页</a>
        </li>
    `);
}

function changePage(page) {
    currentPage = page;
    loadData();
}

function openAddModal() {
    $('#modalTitle').text('新增停车记录');
    $('#recordForm')[0].reset();
    loadAllLots();
    $('#spaceId').empty();
    $('#vehicleId').empty();
    loadAllUsers();
    $('#id').val('');
    modal.show();
}

function openEditModal(id) {
    $.get('/api/parking-record/' + id, function(res) {
        if (res.code === 200) {
            const d = res.data;
            $('#id').val(d.id);
            $('#entryTime').val(d.entryTime);
            $('#exitTime').val(d.exitTime);
            $('#status').val(d.status);
            loadAllLots();
            loadAllUsers();

            $('#lotId').val(d.lotId);
            $('#lotId').trigger('change');
            const checkSpaceIdLoaded = setInterval(() => {
                if ($('#spaceId option').length > 0) {
                    $('#spaceId').val(d.spaceId);
                    clearInterval(checkSpaceIdLoaded);
                }
            }, 50);

            $('#userId').val(d.userId);
            $('#userId').trigger('change');
            const checkVehicleIdLoaded = setInterval(() => {
                if ($('#vehicleId option').length > 0) {
                    $('#vehicleId').val(d.vehicleId);
                    clearInterval(checkVehicleIdLoaded);
                }
            }, 50);

            $('#modalTitle').text('编辑停车记录');
            modal.show();
        } else {
            alert(res.message);
        }
    });
}

function formToJson($form) {
    const unindexed_array = $form.serializeArray();
    const indexed_array = {};
    $.map(unindexed_array, function(n, i){
        indexed_array[n['name']] = n['value'];
    });
    return indexed_array;
}

function save() {
    const id = $('#id').val();
    const method = id ? 'PUT' : 'POST';
    const url = id ? '/api/parking-record/' + id : '/api/parking-record';
    const formData = formToJson($('#recordForm'));

    console.log('Sending data:', formData);

    $.ajax({
        url: url,
        method: method,
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(res) {
            if (res.code === 200) {
                modal.hide();
                loadData();
            } else {
                alert(res.message);
            }
        }
    });
}

function deleteItem(id) {
    if (confirm('确定要删除吗？')) {
        $.ajax({
            url: '/api/parking-record/' + id,
            method: 'DELETE',
            success: function(res) {
                if (res.code === 200) {
                    loadData();
                } else {
                    alert(res.message);
                }
            }
        });
    }
}

function search() {
    currentPage = 1;
    loadData();
}

function resetSearch() {
    $('#searchForm')[0].reset();
    search();
}

function loadAllLots() {
    $.get('/api/parking-lot/list', function(res) {
        if (res.code === 200) {
            const select = $('#lotId');
            select.empty();
            select.append('<option value="">请选择停车场</option>');
            res.data.forEach(item => {
                select.append(`<option value="${item.id}">${item.name}</option>`);
            });
        }
    });
}

function loadSpacesByLotId(lotId) {
    $.get('/api/parking-space/listByLotId?lotId=' + lotId, function(res) {
        if (res.code === 200) {
            const select = $('#spaceId');
            select.empty();
            select.append('<option value="">请选择车位</option>');
            res.data.forEach(item => {
                let spaceTypeText = '';
                if (item.spaceType === 1) {
                    spaceTypeText = '普通';
                } else if (item.spaceType === 2) {
                    spaceTypeText = '充电';
                } else if (item.spaceType === 3) {
                    spaceTypeText = '残疾人';
                }
                select.append(`<option value="${item.id}">${item.id} - ${item.spaceNumber} (${spaceTypeText})</option>`);
            });
        }
    });
}

function loadVehiclesByUserId(userId) {
    $.get('/api/vehicle/listByUserId?userId=' + userId, function(res) {
        if (res.code === 200) {
            const select = $('#vehicleId');
            select.empty();
            select.append('<option value="">请选择车辆</option>');
            res.data.forEach(item => {
                let vehicleTypeText = '';
                if (item.vehicleType === 1) {
                    vehicleTypeText = '小型车';
                } else if (item.vehicleType === 2) {
                    vehicleTypeText = '中型车';
                } else if (item.vehicleType === 3) {
                    vehicleTypeText = '大型车';
                }
                select.append(`<option value="${item.id}">${item.plateNumber} (${vehicleTypeText})</option>`);
            });
        } else {
            alert(res.message);
        }
    });
}

function loadAllUsers() {
    $.get('/api/user/list', function(res) {
        if (res.code === 200) {
            const select = $('#userId');
            select.empty();
            select.append('<option value="">请选择用户</option>');
            res.data.forEach(item => {
                select.append(`<option value="${item.id}">${item.username}</option>`);
            });
        }
    });
}
</script>
</div>